package com.zy.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zy.common.constant.UserConstants;
import com.zy.common.core.domain.entity.SysUser;
import com.zy.common.utils.BeanCopyUtils;
import com.zy.common.utils.sql.StringUtils;
import com.zy.common.core.page.TableDataInfo;
import com.zy.common.core.domain.PageQuery;
import com.zy.web.domain.ZyUser;
import com.zy.web.domain.bo.ZyUserBo;
import com.zy.web.domain.vo.ZyUserVo;
import com.zy.web.mapper.ZyUserMapper;
import com.zy.web.repository.ZyUserRepository;
import com.zy.web.service.IZyUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 用户Service业务层处理
 *
 * @author zy
 * @date 2024-02-25
 */
@RequiredArgsConstructor
@Service
public class ZyUserServiceImpl implements IZyUserService {

    private final ZyUserRepository repository;
    private final ZyUserMapper mapper;

    /**
     * 查询用户
     */
    @Override
    public ZyUserVo queryById(String id){
        return repository.findById(id).map(v -> com.zy.common.utils.BeanCopyUtils.copy(v, ZyUserVo.class)).orElse(null);
    }

    /**
     * 查询用户列表
     */
    @Override
    public TableDataInfo<ZyUserVo> queryPageList(ZyUserBo bo, PageQuery pageQuery) {
        Page<ZyUser> result = repository.findAll(getSpecification(bo), pageQuery.pageable());
        return TableDataInfo.build(result, ZyUserVo.class);
    }

    /**
     * 查询用户列表
     */
    @Override
    public List<ZyUserVo> queryList(ZyUserBo bo) {
        return repository.findAll(getSpecification(bo)).stream()
            .map(v -> com.zy.common.utils.BeanCopyUtils.copy(v, ZyUserVo.class))
            .collect(Collectors.toList());
    }

    private Specification<ZyUser> getSpecification(ZyUserBo bo) {
        return (root, query, cb) -> {
            Map<String, Object> params = bo.getParams();
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(bo.getId())) {
                    predicates.add(cb.equal(root.get("id"), bo.getId()));
            }
            if (bo.getCreateBy() != null) {
                    predicates.add(cb.equal(root.get("createBy"), bo.getCreateBy()));
            }
            if (bo.getCreateTime() != null) {
                    predicates.add(cb.equal(root.get("createTime"), bo.getCreateTime()));
            }
            if (bo.getUpdateBy() != null) {
                    predicates.add(cb.equal(root.get("updateBy"), bo.getUpdateBy()));
            }
            if (bo.getUpdateTime() != null) {
                    predicates.add(cb.equal(root.get("updateTime"), bo.getUpdateTime()));
            }
            if (StringUtils.isNotBlank(bo.getLxfs())) {
                    predicates.add(cb.equal(root.get("lxfs"), bo.getLxfs()));
            }
            if (StringUtils.isNotBlank(bo.getPassword())) {
                    predicates.add(cb.equal(root.get("password"), bo.getPassword()));
            }
            if (StringUtils.isNotBlank(bo.getSf())) {
                    predicates.add(cb.equal(root.get("sf"), bo.getSf()));
            }
            if (StringUtils.isNotBlank(bo.getUsername())) {
                    predicates.add(cb.like(root.get("uesrname"), "%" + bo.getUsername() + "%"));
            }
            if (StringUtils.isNotBlank(bo.getXh())) {
                    predicates.add(cb.equal(root.get("xh"), bo.getXh()));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    /**
     * 新增用户
     */
    @Override
    public Boolean insertByBo(ZyUserBo bo) {
        ZyUser add = com.zy.common.utils.BeanCopyUtils.copy(bo, ZyUser.class);
        validEntityBeforeSave(add);
        repository.saveAndFlush(add);
        bo.setId(add.getId());
        return true;
    }

    /**
     * 新增用户
     */
    @Override
    public Boolean insertUser(ZyUser add) {
        validEntityBeforeSave(add);
        ZyUser zyUser = repository.saveAndFlush(add);
        add.setId(zyUser.getId());
        return true;
    }

    /**
     * 修改用户
     */
    @Override
    public Boolean updateByBo(ZyUserBo bo) {
        ZyUser update = com.zy.common.utils.BeanCopyUtils.copy(bo, ZyUser.class);
        validEntityBeforeSave(update);
        return repository.save(update) != null;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZyUser entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        repository.deleteAllById(ids);
        return true;
    }
    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(ZyUser user) {
        ZyUser zyUser = mapper.selectUserByUserNameOrPhone(user.getUsername());

//        boolean exist = mapper.exists(new LambdaQueryWrapper<ZyUser>()
//                .eq(v->user.getUsername(), user.getUsername())
//                .ne(ObjectUtil.isNotNull(user.getId()), v->user.getId(), user.getId()));
        if (zyUser != null) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

}
